package com.javabasic.algorithm.leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @author mir.xiong
 * @version 1.0
 * @description
 * @see
 * @since Created by work on 2022/6/19 21:53
 */
public class MostFrequentSubtreeSum {

    private Set<Integer> sumSet;
    private Map<Integer, Integer> sumNumMap;
    private int maxNum = 0;

    /**
     * 递归+记忆(备忘录)
     * @param root
     * @return
     */
    public int[] findFrequentTreeSum(TreeNode root) {

        sumSet = new HashSet<>();

        sumNumMap = new HashMap<>(16);

        calculateSum(root);
        int[] result = new int[sumSet.size()];

        int index = 0;
        for (Integer integer : sumSet) {
            result[index++] = integer;
        }
        sumNumMap.forEach((k,v) -> {
            System.out.println("k = " + k + " v = " + v);
        });
        return result;
    }

    private int calculateSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int sum = root.val;
        if (root.left != null) {
            sum += calculateSum(root.left);
        }
        if (root.right != null) {
            sum += calculateSum(root.right);
        }
        Integer num = sumNumMap.getOrDefault(sum, 0);
        num++;

        if (num > maxNum) {
            maxNum = num;
            sumSet.clear();
            sumSet.add(sum);
        } else if (num == maxNum) {
            sumSet.add(sum);
        }
        sumNumMap.put(sum, num);
        return sum;
    }
}
